import { useState, useRef } from 'react';
import { Card, Form, Input, Button, message } from 'antd';
import { editAccount } from '@/api/account';

const Edit = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const user = JSON.parse(sessionStorage.getItem('user'));

  // 提交表单
  const submitForm = async () => {
    try {
      // 验证表单
      const values = await form.validateFields();
      
      // 添加用户ID到表单数据
      const formData = {
        ...values,
        id: user.id
      };

      setLoading(true);
      const res = await editAccount(formData);
      console.log(res);
      message.success('修改成功，请重新登录');
      form.resetFields();
    } catch (error) {
      if (error.errorFields) {
        // 表单验证错误
        message.error('表单验证失败，请检查输入');
      } else {
        // API调用错误
        console.error('修改失败', error);
        message.error('修改失败');
      }
    } finally {
      setLoading(false);
    }
  };

  // 重置表单
  const resetForm = () => {
    form.resetFields();
  };

  return (
    <div className="password-change-container">
      <Card 
        title="修改密码" 
        className="password-change-card"
        headStyle={{ textAlign: 'center', fontWeight: 'bold', fontSize: '18px' }}
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            oldPwd: '',
            newPwd: '',
            newPwd1: ''
          }}
        >
          <Form.Item
            label="原密码"
            name="oldPwd"
            rules={[
              { required: true, message: '请输入原密码' },
              { min: 6, message: '密码长度不能少于6位' }
            ]}
          >
            <Input.Password placeholder="请输入原密码" />
          </Form.Item>

          <Form.Item
            label="新密码"
            name="newPwd"
            rules={[
              { required: true, message: '请输入新密码' },
              { min: 6, message: '密码长度不能少于6位' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('oldPwd') !== value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('新密码不能与原密码相同'));
                },
              }),
            ]}
          >
            <Input.Password placeholder="请输入新密码" />
          </Form.Item>

          <Form.Item
            label="确认新密码"
            name="newPwd1"
            dependencies={['newPwd']}
            rules={[
              { required: true, message: '请再次输入新密码' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('newPwd') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致'));
                },
              }),
            ]}
          >
            <Input.Password placeholder="请再次输入新密码" />
          </Form.Item>

          <Form.Item>
            <Button 
              type="primary" 
              onClick={submitForm} 
              loading={loading}
              block
            >
              确认修改
            </Button>
            <Button onClick={resetForm} block style={{ marginTop: 10 }}>
              重置
            </Button>
          </Form.Item>
        </Form>
      </Card>

      <style jsx>{`
        .password-change-container {
          display: flex;
          justify-content: center;
          align-items: center;
          height: 100vh;
          background-color: #f0f2f5;
          padding: 20px;
        }
        .password-change-card {
          width: 450px;
          border-radius: 8px;
          box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }
        .ant-form-item {
          margin-bottom: 22px;
        }
      `}</style>
    </div>
  );
};

export default Edit;